<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Zuzhi extends Backend
{

    /**
     * Zuzhi模型对象
     * @var \app\admin\model\Zuzhi
     */
    protected $model = null;
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Zuzhi;
        // 必须将结果集转换为数组
        $ruleList = Db::name("zuzhi")->where('delete_id',0)->order('id ASC')->select();

        $admin = $this->auth->getUserInfo();
        $ruleList = selectMenus_zuzhi1($admin['zuzhi']);
//        dump($ruleList);die;
        foreach ($ruleList as $k => &$v) {
            $v['name'] = __($v['name']);
        }

        Tree::instance()->init($ruleList)->icon = ['&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'];
        if($admin['id'] == 1){
            $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
        }else{
            $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($admin['zuzhi']), 'name');
        }
        $ruledata = selectMenus_zuzhi2($admin['zuzhi']);
        $this->view->assign('ruledata', $ruledata);
        $jigoudata = [''=>'','直属业务'=>'直属业务','直接业务'=>'直接业务','分支机构'=>'分支机构','合作商'=>'合作商','查勘机构'=>'查勘机构','招商业务'=>'招商业务','合作业务 '=>'合作业务'];
        $this->view->assign('jigoudata', $jigoudata);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index(){
        if ($this->request->isAjax()) {
            $list = $this->rulelist;
            foreach ($list as &$v){
                $pay_name = Db::name('pay_channel')->whereIn('id',$v['pay_channel_id'])->column('name');
                if($pay_name) $v['pay_name'] = implode(',',$pay_name);
                else $v['pay_name'] = '';
            }
            $total = count($this->rulelist);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
//    public function del($ids = null)
//    {
//        if (false === $this->request->isPost()) {
//            $this->error(__("Invalid parameters"));
//        }
//        $ids = $ids ?: $this->request->post("ids");
//        if (empty($ids)) {
//            $this->error(__('Parameter %s can not be empty', 'ids'));
//        }
//        $pk = $this->model->getPk();
//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds)) {
//            $this->model->where($this->dataLimitField, 'in', $adminIds);
//        }
//        $list = $this->model->where($pk, 'in', $ids)->select();
//
//        $count = 0;
//        Db::startTrans();
//        try {
//            foreach ($list as $item) {
//                $count += $item->save(['delete_id'=>1]);
//            }
//            Db::commit();
//        } catch (PDOException|Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
//        if ($count) {
//            $this->success();
//        }
//        $this->error(__('No rows were deleted'));
//    }

    public function getselect(){
        $yw_come = $this->request->post("yw_come");
        $admin_id = $this->auth->id;
        if($admin_id == 1){
            $res = db('zuzhi')->where('jigou',$yw_come)->where('delete_id',0)->select();
        }else{
            $res = db('zuzhi')->where('jigou',$yw_come)->where('delete_id',0)->select();
            $zid_info = db('admin')->where('id', $admin_id)->find();
            $cateid = $zid_info['zuzhi'];
            $arr_all = $this->getSubs1($res, $cateid);
            $arr_all[] = $cateid;
            $id = implode(',', $arr_all);
            $res = db('zuzhi')
                ->where('jigou',$yw_come)
                ->where('id','in',$id)
                ->where('delete_id',0)
                ->select();
        }
        if($res){
            $res = Loader::model('Zuzhi')->selectMenus_res($res);
        }
        $this->success('','',$res);

    }
    function getSubs1($categorys, $catId = 0, $level = 1)
    {
        $ids = array(); // 用于存储所有 id
        foreach ($categorys as $item) {
            if ($item['pid'] == $catId) {
                $ids[] = $item['id']; // 收集当前 id
                // 递归调用，确保总是返回数组
                $childIds = $this->getSubs1($categorys, $item['id'], $level + 1);
                if (is_array($childIds)) {
                    $ids = array_merge($ids, $childIds);
                }
            }
        }
        return $ids; // 返回 id 数组
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function zhifu($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if($ids == 1){
            return json(['code' => -1, 'msg' => '禁止删除']);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        // 启动事务
        Db::startTrans();
        try {
            Db::name('zuzhi')->where('id', 'in', $ids)->update(['delete_id'=>1]);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '请求成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage().'，异常行：'.$e->getLine().'，异常路径：'.$e->getfile()]);
        }
    }

    public function getUser(){
        $yw_class = $this->request->post("yw_class");
        $res =Db::name('admin')->where('zuzhi',$yw_class)->field('id,number,username')->select();
        $this->success('','',$res);
    }

}
